import { ajaxGet } from '@/util'
export default ({
  state: {
    user: {
      userToken: localStorage.getItem('token'),
      name: localStorage.getItem('name'),
      userInfo: ''
    },
    userLoading: false,
    menu: JSON.parse(localStorage.getItem('menu') || '[]')
  },
  mutations: {
    setLoading(state, param) {
      let [key, loading] = param
      state[key] = loading
    },
    setUser(state, { name, token }) {
      localStorage.setItem('token', token)
      localStorage.setItem('name', name)
      state.user.userToken = token
      state.user.name = name
    },
    setUserInfo(state, data) {
      state.user.userInfo = data
    }
  },
  actions: {
    isShowMeta({ commit, dispatch, state }) {
      return new Promise((resolve, reject) => {
        ajaxGet('/menu/getMainMenu').then(data => {
          localStorage.setItem('menu', JSON.stringify(data))
          state.menu = data 
          resolve(data)
        })
      })
    },
    getInfo({ commit, dispatch, state }) {
      return new Promise((res, reject) => {
        ajaxGet('/user/info').then(data => {
          commit('setUserInfo', data)
          res(data)
        }).catch(data => {
          reject(data)
        })
      })
    },
    userLogin({ commit, dispatch, state }, { name, token }, reload) {
      if (state.userLoading === false || reload) {
        commit('setLoading', ['userLoading', true])
        commit('setUser', { name, token })
        commit('setLoading', ['userLoading', false])
      } else {
        return state.user
      }
    }
  },
  getters: {
    userInfo: (state) => {
      return state.user.userInfo
    },
    user: (state) => {
      let win = window.parent || window
      if (win !== window) {
        return window.parent.app.$store.getters.user
      }
      return state.user
    },
    userMenu: (state) => {
      return state.menu
    }
  }
})
